package com.example.myanimator.utils

import android.animation.ValueAnimator
import java.lang.reflect.Field

/**
 * @author tgw
 * @date 2021/12/13
 * @describe android 5.0 属性动画失效
 */
object ValueAnimatorUtil {
    /**
     * 如果动画被禁用，则重置动画缩放时长
     */
    fun resetDurationScaleIfDisable() {
        if (durationScale == 0f) resetDurationScale()
    }

    /**
     * 重置动画缩放时长
     */
    private fun resetDurationScale() {
        try {
            animatorField.setFloat(null, 1f)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private val durationScale: Float
        private get() = try {
            animatorField.getFloat(null)
        } catch (e: Exception) {
            e.printStackTrace()
            (-1).toFloat()
        }

    @get:Throws(NoSuchFieldException::class)
    private val animatorField: Field
        private get() {
            val field = ValueAnimator::class.java.getDeclaredField("sDurationScale")
            field.isAccessible = true
            return field
        }
}